import request, { serviceMaster } from '../utils/request';
import { API } from '../utils/config';

/**
 * 获取角色列表
 * @param params 查询参数
 * @returns Promise
 */
export function getRoleList(params?: any) {
  return serviceMaster({
    url: API.ROLES,
    method: 'get',
    params
  });
}

/**
 * 获取角色详情
 * @param id 角色ID
 * @returns Promise
 */
export function getRoleDetail(id: string) {
  return serviceMaster({
    url: `${API.ROLES}/${id}`,
    method: 'get'
  });
}

/**
 * 创建角色
 * @param data 角色数据
 * @returns Promise
 */
export function createRole(data: any) {
  // 构建符合LeanCloud角色API的数据格式
  const roleData = {
    name: data.name,
    ACL: {
      "*": {
        "read": true
      }
    },
    // 将permissions和其他自定义字段放入属性中
    permissions: data.permissions,
    description: data.description,
    displayName: data.displayName,
    users: data.users || []
  };

  return serviceMaster({
    url: API.ROLES,
    method: 'post',
    data: roleData
  });
}

/**
 * 更新角色
 * @param id 角色ID
 * @param data 角色数据
 * @returns Promise
 */
export function updateRole(id: string, data: any) {
  // 构建更新数据，只包含需要更新的字段
  const updateData: any = {};
  
  if (data.name) {
    updateData.name = data.name;
  }
  
  if (data.permissions) {
    updateData.permissions = data.permissions;
  }
  
  if (data.description) {
    updateData.description = data.description;
  }

  if (data.displayName) {
    updateData.displayName = data.displayName;
  }

  return serviceMaster({
    url: `${API.ROLES}/${id}`,
    method: 'put',
    data: updateData
  });
}

/**
 * 删除角色
 * @param id 角色ID
 * @returns Promise
 */
export function deleteRole(id: string) {
  return serviceMaster({
    url: `${API.ROLES}/${id}`,
    method: 'delete'
  });
} 